const api = require('../../../api/index.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    oaderTab: [
      {
        name: '全部',
        active: true
      },
      {
        name: '待支付',
        active: false
      },
      {
        name: '待使用',
        active: false
      },
      {
        name: '已完成',
        active: false
      },
      {
        name: '已关闭',
        active: false
      }],
      orderStatus: {
        status: "",
        page: 5
      },
      cancelIndex: "",// 取消的当前index
      orderData0: [], // 全部
      orderData1: [], // 待支付
      orderData2: [], 
      orderData3: [],
      orderData4: [],
      orderSta: [true,true,true,true] ,// 控制试图切换变化
      noneOrder: false, // 没有订单状态
      orderConfirm: false, // 取消按钮状态
      orderId: "", // 需要取消订单的id
      arrData:[], // 当前渲染数据
      onPull: 0,
      page:[1,1,1,1,1], // 记录页面上拉加载页码
      tabIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.onBottom("1", '0', "orderData0").then((res) => {
      this.noOrder()
      console.log(this.data.arrData.length)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
     //this.refresh();
    App.zhuge.track('我的订单列表', {})
  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onPullDownRefresh: function(){
    let currentTab = "orderData" + this.data.tabIndex;
    let index = this.data.tabIndex; // 当前tab的index
    // 动态设置导航条标题  
    wx.setNavigationBarTitle({
      title: '加载中'
    });
    wx.showNavigationBarLoading(); //在标题栏中显示加载图标  
    this.data.page = [1, 1, 1, 1, 1];
    this.setData({
      orderData0: [], // 全部
      orderData1: [], // 待支付
      orderData2: [],
      orderData3: [],
      orderData4: [],
      arrData: []
    })
    this.onBottom("1", index, currentTab).then((res) => {
      console.log(res)
      wx.hideNavigationBarLoading();
      wx.setNavigationBarTitle({
        title: '我的订单'
      });
      wx.showToast({
        title: '刷新成功',
      })
      // this.setData({
      //   arrData: this.data.orderData2
      // })
      this.noOrder()
      console.log(this.data.arrData.length)
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let onpull = this.data.onPull
    if (onpull == 0){
      this.data.page[0] = ++this.data.page[0];
      this.onBottom(this.data.page[0],'0', "orderData0")
    }
    
    if (onpull == 1) {
      this.data.page[1] = ++this.data.page[1];
      this.onBottom(this.data.page[1], '1',  "orderData1")
      console.log(22)
    }

    if (onpull == 2) {
      this.data.page[2] = ++this.data.page[2];
      this.onBottom(this.data.page[2], '1', "orderData2")
      console.log(33)
    }
    if (onpull == 3) {
      this.data.page[3] = ++this.data.page[3];
      this.onBottom(this.data.page[3], '1', "orderData3")
      console.log(44)
    }
    if (onpull == 4) {
      this.data.page[4] = ++this.data.page[4];
      this.onBottom(this.data.page[4], '1', "orderData4")
      console.log(55)
    }
  },
  onBottom: function(pageNum,status,key){ // 上拉到底重新请求数据 接收一个num页数  一个保存的Arr key
    wx.showLoading({
      title: '加载中',
    })

    return new Promise((resolve, reject) => {
      // ... some code

      this.getOrderFormData({ status: status, page: pageNum }, (res) => {
        this.setData({
          [key]: this.data[key].concat(res)
        })
        this.setData({
          arrData: this.data[key]
        })
        wx.hideLoading()
        if (res.length <= 0) {
          wx.showToast({
            title: '没有更多数据了',
            icon: "none"
          })
        }
        resolve(res);
        console.log(this.data.arrData)
      })

      // if (/* 异步操作成功 */){
      //   resolve(value);
      // } else {
      //   reject(error);
      // }
    });


  },
  tabToggle: function (event) { //tab 切换功能
    let index = event.currentTarget.dataset.index;
    this.data.tabIndex = index;
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
    if (index == 0) {
      this.data.orderData0 = []
      this.onBottom("1", '0', "orderData0").then((res) =>{
        this.noOrder()
        console.log(this.data.arrData.length)
      })
      this.setData({
        arrData: this.data.orderData0
      })
      App.zhuge.track('我的订单-全部', {})
      console.log(this.data.orderData1)
    }

    if(index == 1){
      this.data.orderData1 = []
      this.onBottom('1', '1', "orderData1").then((res) => {
        this.noOrder()
        console.log(this.data.arrData.length)
      })
      this.setData({
        arrData: this.data.orderData1
      })
      App.zhuge.track('我的订单-待支付', {})
      console.log(this.data.orderData1)
    }

    if (index == 2) {
      this.data.orderData2 = []
      this.onBottom('1', '2', "orderData2").then((res) => {
        this.noOrder()
        console.log(this.data.arrData.length)
      })
      this.setData({
        arrData: this.data.orderData2
      })
      App.zhuge.track('我的订单-待使用', {})
    }

    if (index == 3) {
      this.data.orderData3 = []
      this.onBottom('1', '3', "orderData3").then((res) => {
        this.noOrder()
        console.log(this.data.arrData.length)
      })
      this.setData({
        arrData: this.data.orderData3
      })
      App.zhuge.track('我的订单-已完成', {})
    }
    if (index == 4) {
      this.data.orderData4 = []
      this.onBottom('1', '4', "orderData4").then((res) => {
        this.noOrder()
        console.log(this.data.arrData.length)
      })
      this.setData({
        arrData: this.data.orderData4
      })
      App.zhuge.track('我的订单-已关闭', {})
    }
    this.data.oaderTab.forEach((item, index) => { // 设置切换样式
      let key = `oaderTab[${index}].active`;
        this.setData({
          [key]: false
        })
    })
    this.setData({
      [`oaderTab[${index}].active`]: true,
      onPull: index
    })
  },
  getOrderFormData: function(data, callback) { // 获取订单数据
    api.orderForm(data, (res) => {
      console.log(res)
      callback(res.data.result);
    })
  },
  goPlay: function(e){
    let _this = this;
    let oppids = wx.getStorageSync('openid').openid;
    let data = {
      'order_sn': e.currentTarget.dataset.order_sn,
      'num': e.currentTarget.dataset.num,
      'totalprice': parseInt(e.currentTarget.dataset.totalprice),
      'type':1,
      'openid_wechat': oppids,
      'url':'Community/Order/pay'
    }
 
    api.play(data, (res) => {
    let playData = res.data.result;
      wx.requestPayment({
        'timeStamp': playData.timeStamp,
        'nonceStr': playData.nonceStr,
        'package': playData.package,
        'signType': playData.signType,
        'paySign': playData.paySign,
        'success': function (res) {
          console.log('交钱成功')
        _this.refresh(); // 交钱成功  重新刷新当前视图
          console.log(data.order_sn)
          App.zhuge.track('我的订单-支付成功', {})
          wx.navigateTo({
            url: `/pages/my/orderDetails/orderDetails?order_id=${data.order_sn}`,
          })
          console.log(res)
        },
        'fail': function (res) {
          App.zhuge.track('我的订单-支付失败', {})
          wx.showToast({
            title: '支付失败',
            icon: 'none'
          })
          console.log('交钱失败')
          console.log(res)
        }
      })
      console.log(res)
     })

  },
  cancelOrder: function (e) { // 取消订单
    let orderId = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    this.setData({
      orderConfirm: true,
      orderId: orderId,
      cancelIndex: index
    })
    App.zhuge.track('我的订单-点击取消订单', {})
  },
  cancel: function(){
    let _this = this;
    let onpull = this.data.onPull; // 当前tab 所在状态
    let id = this.data.orderId;
    let index = this.data.cancelIndex; // 删除当前的数组的index
    this.data.arrData[index].order_status = 4;
    if (onpull == 0){
      this.data.orderData0[index].order_status = 4;
      this.setData({
        arrData: this.data.arrData
      })
      console.log('修改成功')
    }
    if (onpull == 1){
      
      let Arr = this.SerializeArr(this.data.arrData,index) // 删除后得到的列表
        console.log(Arr)
        this.setData({
          arrData: Arr
        })
      console.log('取消成功');
      App.zhuge.track('取消订单-取消成功', {});
    }
    api.cancelOrder(id, (res) => {
      this.setData({
        orderConfirm: false,
      })
      wx.showToast({
        title: '你已经成功取消当前订单',
        icon: "none"
      })
    })
  },
  confirmHidden: function(){
    this.setData({
      orderConfirm: false
    })
  },
  SerializeArr: function (arrData,index) { //删除指定index 数组
    var temArray = [];
    for (var i = 0; i < arrData.length; i++) {
      if (i != index) {
        temArray.push(arrData[i]);
      }
    }
    return temArray;
  },
  noOrder: function() {
    if (this.data.arrData <= 0) {
      this.setData({
        noneOrder: true
      })
    } else {
      this.setData({
        noneOrder: false
      })
    }
  },
  refresh: function(){ // 支付后  刷新当前视图
 
    let currentTab = "orderData" + this.data.tabIndex;
    let index = this.data.tabIndex; // 当前tab的index
    // 动态设置导航条标题  
   // wx.showNavigationBarLoading(); //在标题栏中显示加载图标  
    this.data.page = [1, 1, 1, 1, 1];
    this.setData({
      orderData0: [], // 全部
      orderData1: [], // 待支付
      orderData2: [],
      orderData3: [],
      orderData4: [],
      arrData: []
    })
    this.onBottom("1", index, currentTab).then((res) => {
      
    //  wx.hideNavigationBarLoading();
      wx.setNavigationBarTitle({
        title: '我的订单'
      });
      // this.setData({
      //   arrData: this.data.orderData2
      // })
      this.noOrder()
      console.log(this.data.arrData.length)
    })
  }
})